/*
 * @lc app=leetcode.cn id=811 lang=cpp
 *
 * [811] 子域名访问计数
 */

// @lc code=start
class Solution {
public:
    vector<string> subdomainVisits(vector<string> &cpdomains) {
        unordered_map<string, int> counts;
        for (auto &x : cpdomains) {
            int idx = x.find(' ');
            int count = stoi(x.substr(0, idx));
            string domain = x.substr(idx + 1);
            counts[domain] += count;
            for (int i = 0; i < domain.size(); i++) {
                if (domain[i] == '.') {
                    string subdomain = domain.substr(i + 1);
                    counts[subdomain] += count;
                }
            }
        }

        vector<string> ans;
        for (auto &[subdomain, count] : counts) {
            ans.push_back(to_string(count) + ' ' + subdomain);
        }

        return ans;
    }
};
// @lc code=end
